<script lang="ts" setup>

const { getRealNameFromUserInfoByFiatCurrencyId } = useCurrencyData()
const { t, locale } = useI18n();
const route = useRoute()
const showSheet = ref(false)
const selectedAccount = ref()
const isDelete = ref(false)
const setDefault = ref(false)
const editRef = ref()
const transfer = useTransferStore()
import { useForm } from 'vee-validate';
import * as yup from 'yup';
import { Form } from 'vee-validate';
definePageMeta({
    layout: 'header-back',
    title: 'account_management'
})

import type { BankCard } from '~/apis/types'


/** 获取已经绑定银行卡和钱包, 支持的取款类型, */
const { runAsync: runAsyncWithdrawBankcard, data: allTypeBankcardData, loading: loadingBankcard } = useRequest(ApiFinanceWithdrawBankcard)


application.allSettled([
  runAsyncWithdrawBankcard({ currency_id:  transfer.data.currency_id, withdraw_type: '1' })
])

/** 巴西货币使用pix */
const isPix = computed(() => {
    return  transfer.data.currency_id === '702'
})

const channelLabel = computed(() => {
  if(isPix.value) {
    return t('pix_type')
  }
  if(WithdrawMethod.BANK.toString() ===  transfer.data.type){
    return t('choose_bank')
  }else{
    return t('choose_wallet')
  }
})
const accountLabel = computed(() => {
  if(isPix.value) {
    return t('pix_account')
  }
  if(WithdrawMethod.BANK.toString() ===  transfer.data.type){
    return t('bank_account')
  }else if(WithdrawMethod.ALIPAY.toString() ===  transfer.data.type){
    return t('alipay_account')
  }
  else{
    return t('wallet_address')
  }
})


const { run: runDelete, loading: deleteBankcardLoading } = useRequest(ApiMemberBankcardDelete, {
  async onSuccess() {
    message.success(t('delete_success'))
    showSheet.value = false
    runAsyncWithdrawBankcard({ currency_id:  transfer.data.currency_id as string, withdraw_type: '1' })
  },
})

/** 编辑银行卡 */
const {
  runAsync: runUpdateBankcard,
  loading: updateBankcardLoading,
} = useRequest(ApiMemberBankcardUpdate, {
  onSuccess() {
    message.success(t('edit_success'))
  },
})

const accountList = computed(() => allTypeBankcardData.value?.d?.filter?.(item => item.currency_id ===  transfer.data.currency_id && item.type_id ===  transfer.data.type_id) || [])

const schema = yup.object().shape({
  bank_account: yup.string().required(t('accountLabel')),
  password: yup.string().required(t('money_password_placeholder')).min(6, '密码至少需要6个字符'),
  open_name: yup.string(),
  cpf: isPix.value ? yup.string().required('CPF'): yup.string(),
  address: WithdrawMethod.BANK.toString() ===  transfer.data.type ? yup.string().required(t('recharge_target_account_address')) : yup.string()
});

const { resetForm, setFieldValue, values } = useForm({
  validationSchema: schema,
  initialValues: {
    bank_account: '',
    password: '',
    address: "",
    cpf: '',
    open_name: getRealNameFromUserInfoByFiatCurrencyId( transfer.data.currency_id as CurrencyCode) ?? ''
  }
})

function handleEdit(){
  const { values } = editRef.value
    if(isDelete.value){
        runDelete({
          id: selectedAccount.value.id,
          pay_password: values.password,
          auth_type: 2,
        })
        return
    }
    // 编辑
    runUpdateBankcard({
      ...selectedAccount.value,
      currency_id:  transfer.data.currency_id,
      bank_name: selectedAccount.value.bank_name,
      bank_account: values.bank_account,
      is_default: setDefault.value ? 1 : 2,
      pay_password: values.password,
      country: selectedAccount.value.country,
      city: '',
      address: selectedAccount.value.address,
      auth_type: 2,
      bank_id: selectedAccount.value.bank_id,
    })
}

function setShowSheet(item: BankCard, deleteIt: boolean) {
    showSheet.value = true;
    selectedAccount.value = item;
    isDelete.value = deleteIt
}

</script>

<template>
  <div class="m-[1rem] px-[1rem] rounded-[.5rem] bg-bg-black-4 mb-[3.75rem]">
    <AppBaseSkeletonLoader v-if="loadingBankcard" class="py-[1rem]"/>
    <template v-else>
      <BaseEmpty v-if="!accountList?.length"/>
      <template v-for="item in accountList" :key="item.id">
          <AppBankAccountItem @delete="() => setShowSheet(item, true)" @edit="() => setShowSheet(item, false)" :bank_name="item.bank_name" :open_name="values.open_name" :bank_account="item.bank_account" :bank_id="item.bank_id"/>
      </template>
    </template>
    <BaseSheet
        v-model="showSheet"
        :title="isDelete ? t('confirm_for_delete') : t('edit')"
      >
        <div class="text-center" v-if="isDelete">{{t('confirm_if_delete')}}</div>
        <div class="px-[1rem] mb-[2rem]">
            <Form :validation-schema="schema" @submit="handleEdit" ref="editRef">
                <BaseInput required class="mt-[1rem]" :label="t('real_name')" name="open_name" :modelValue="values.open_name" :disabled="!!values.open_name">
                </BaseInput>
                <BaseInput required class="mt-[1rem]" :label="channelLabel" name="bank_name" :modelValue="selectedAccount.bank_name" :disabled="isDelete || WithdrawMethod.WALLET.toString() ===  transfer.data.type" v-if="WithdrawMethod.ALIPAY.toString() !==  transfer.data.type">
                </BaseInput>
                <BaseInput required class="mt-[1rem]" :label="t('recharge_target_account_address')" name="address" :modelValue="selectedAccount.address" :disabled="isDelete" v-if="WithdrawMethod.BANK.toString() ===  transfer.data.type && !isPix">
                </BaseInput>
                <BaseInput required class="mt-[1rem]" :label="accountLabel" name="bank_account" :modelValue="selectedAccount.bank_account" :disabled="isDelete">
                </BaseInput>
                <BaseInput required class="mt-[1rem]" label="CPF" name="cpf" :modelValue="selectedAccount.bank_area_cpf" :disabled="isDelete" v-if="isPix">
                </BaseInput>
                <BaseInput required class="mt-[1rem]" :label="t('money_password')" name="password" type="password" :placeholder="t('money_password_placeholder')">
                </BaseInput>
                <BaseCheckbox :checked="setDefault" @click="setDefault = !setDefault" :label="t('set_as_default_account')" class="mt-[.75rem] mb-[1rem]" v-if="!isDelete"/>
                <div class="flex gap-[.625rem]">
                    <BaseButton :loading="false" @click="showSheet = false" class="w-full h-[2.5rem] mt-[1rem] text-text-black-10 text-[.75rem]" type="secondary">
                    {{t('common_cancel')}}
                    </BaseButton>
                    <BaseButton :loading="isDelete ? deleteBankcardLoading : updateBankcardLoading" class="w-full h-[2.5rem] mt-[1rem] text-text-black-10 text-[.75rem]" html-type="submit">
                    {{isDelete ? t('confirm_delete') : t('confirm_edit')}}
                    </BaseButton>
                </div>
            </Form>
        </div>
    </BaseSheet>
  </div>
</template>

<style lang="scss"></style>
